"use client";

import {
  Button,
  Divider,
  Form,
  Input,
  message,
  Modal,
  Pagination,
  Select,
  Table,
  Tooltip,
} from "antd";
import { MdManageSearch } from "react-icons/md";
import { orgList } from "../../../../utils/static-select";
import { GetDept, GetQeuryList, GetFlow } from "@/app/api/operation/query";
import { useEffect, useState } from "react";
import { FlowSource, Pager, QueryType } from "../../../../utils/publictype";
import { getUserAccount } from "../../../../utils/defender";
import { PlusCircleFilled } from "@ant-design/icons";
import { TiFlowSwitch } from "react-icons/ti";
import { useRouter } from "next/navigation";
import FLow, { dataType } from "@/components/FLow";
import { Edge, Node } from "@xyflow/react";
import Download from "@/components/SingImg";
import { FaFileSignature } from "react-icons/fa6";
import { FaHandPointDown } from "react-icons/fa";
import PushFlow from "@/components/PushFlow";

export default function Query() {
  const [form] = Form.useForm();
  const router = useRouter();
  const [deptS, setDeptS] = useState<{ value: number; label: string }[]>([]);//部門數據
  const [pager, setPager] = useState<Pager>({
    current: 1,//當前頁數
    count: 0,//總數
    pagesize: 10,//每頁數據大小
  });//分頁器

  useEffect(() => {
    setPager({
      ...pager,
      pagesize: Math.floor((document.body.clientHeight - 350) / 55) - 2,//根據用戶屏幕尺寸大小初始化數據條數。
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const [dataSource, setDataSource] = useState<QueryType[]>([]);//查詢參數
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [flowData, setFlowData] = useState<dataType>({
    docid: "",
    nodes: [],
    edges: [],
  });//繪製流程數據
  const [isModalOpenImg, setIsModalOpenImg] = useState(false);
  const [isModalOpenPush,setIsModalOpenPush] = useState(false)
  const [curdocid, setCurDocid] = useState("");

  const GetDeptFunc = async (e: number) => {
    const org_code = orgList.filter((item) => item.value === e)[0].label;
    if (org_code === " ") {
      setDeptS([]);
      return false;
    } else {
      const res: any = await GetDept(org_code);
      const temp: { value: number; label: string }[] = [
        { value: 1, label: " " },
      ];
      for (let i = 0; i < res[0].length; i++) {
        temp.push({ value: i + 2, label: res[0][i].code });
      }
      setDeptS(temp);
    }
  };

  //查詢
  const Submit = async () => {
    const docid = form.getFieldValue("docid");
    const org_code =
      form.getFieldValue("org_code") !== undefined
        ? orgList.filter(
            (item) => item.value === form.getFieldValue("org_code")
          )[0].label
        : "";
    const dept =
      deptS.length > 0 && form.getFieldValue("dept") !== undefined
        ? deptS?.filter((item) => item.value === form.getFieldValue("dept"))[0]
            .label
        : "";
    const decade = form.getFieldValue("decade");
    const badge = form.getFieldValue("badge");
    const regex = /^\d{6}$/;
    const regex1 = /^IA\d{12}$/;
    if (decade !== undefined && decade !== "") {
      if (!regex.test(decade)) {
        message.info("請輸入YYYYMM格式的期間");
        return false;
      }
    }
    if (badge !== undefined && badge !== "") {
      if (!regex.test(badge)) {
        message.info("輸入工號的格式不正確");
        return false;
      }
    }
    if (docid !== undefined && docid !== "") {
      if (!regex1.test(docid)) {
        message.info("輸入單號的格式不正確！");
        return false;
      }
    }
    const param = {
      ...pager,
      docid: docid !== undefined ? docid : "",
      org_code: org_code,
      badge: badge !== undefined ? badge : "",
      dept: dept,
      decade: decade !== undefined ? decade : "",
      type: "count",
      username: getUserAccount() as string,
    };
    try {
      const res: any = await GetQeuryList(JSON.stringify(param));
      if (res[0][0].count > 0) {
        setPager({ ...pager, count: res[0][0].count });
        await changeCurr(1);
      } else {
        message.info("此查詢條件下沒有數據");
        setDataSource([]);
        setPager({ ...pager, count: 0 });
      }
    } catch {
      message.error("系統異常");
    }
  };

  //頁數變化
  const changeCurr = async (e: number) => {
    const docid = form.getFieldValue("docid");
    const org_code =
      form.getFieldValue("org_code") !== undefined
        ? orgList.filter(
            (item) => item.value === form.getFieldValue("org_code")
          )[0].label
        : "";
    const dept =
      deptS.length > 0 && form.getFieldValue("dept") !== undefined
        ? deptS?.filter((item) => item.value === form.getFieldValue("dept"))[0]
            .label
        : "";
    const decade = form.getFieldValue("decade");
    const badge = form.getFieldValue("badge");
    const param = {
      ...pager,
      docid: docid !== undefined ? docid : "",
      org_code: org_code,
      badge: badge !== undefined ? badge : "",
      dept: dept,
      decade: decade !== undefined ? decade : "",
      type: "list",
      username: getUserAccount() as string,
      current: e,
    };
    try {
      const res: any = await GetQeuryList(JSON.stringify(param));
      setDataSource(res[0]);
    } catch {
      message.error("系統異常");
    }
  };

  const CheckInfo = (docid: string, type: string) => {
    if (type === "improve") {
      if (
        dataSource.filter((item) => item.docid === docid)[0].is_improve === "否"
      ) {
        message.info("此單沒有改善計劃！");
        return false;
      }
    }
    router.push(`/dashboard/${type}/?docid=${docid}&type=end`);
  };

  //查看流程
  const CehckFlow = async (docid: string) => {
    setIsModalOpen(true);
    if (docid !== flowData.docid) {
      const res: any = await GetFlow(docid);
      const source: FlowSource[] = res[0];
      const nodes: Node[] = [];
      const edges: Edge[] = [];
      let multiFlag = 0;
      //處理數據
      for (let i = 0; i < source.length; i++) {
        const nextFlow = source.filter(
          (item) => item.flow === source[i].flow + 10
        );

        //nodes
        const preNode = nodes.filter(
          (item1) =>
            item1.id ===
            edges.filter((item) => item.target === (i + 1).toString())[0].source
        )[0];
        if (source[i].is_multi === "N") {
          nodes.push({
            id: (i + 1).toString(),
            data: {
              label: `${source[i].flow_phase}---(執行者:${source[i].chinese_name},操作時間:${source[i].last_update_time})`,
            },
            position: {
              x: 100,
              y: nodes.length === 0 ? 0 : preNode.position.y + 150,
            },
            style: {
              background: "cadetblue",
              borderRadius: "5px",
            },
          });
          //edges
          edges.push({
            id: nodes.length.toString() + "-" + (nodes.length + 1).toString(),
            source: nodes.length.toString(),
            target: (nodes.length + 1).toString(),
            label: source[i].approve,
            style: {
              stroke: "brown",
              strokeWidth: 2,
            },
          });
          //多線程
          if (nextFlow.length > 1) {
            edges.push({
              id: nodes.length.toString() + "-" + (nodes.length + 2).toString(),
              source: nodes.length.toString(),
              target: (nodes.length + 2).toString(),
              label: source[i].approve,
              style: {
                stroke: "brown",
                strokeWidth: 2,
              },
            });
          }
        } else {
          multiFlag++;
          nodes.push({
            id: (nodes.length + 1).toString(),
            data: {
              label: `${source[i].flow_phase}---(執行者:${source[i].chinese_name},操作時間:${source[i].last_update_time})`,
            },
            position: {
              x: multiFlag === 2 ? 200 : 0,
              y: preNode.position.y + 150,
            },
            style: {
              background: "lightgreen",
              borderRadius: "5px",
            },
          });

          //多線程轉到單線程
          edges.push({
            id:
              nodes.length.toString() +
              "-" +
              (nodes.length + 3 - multiFlag).toString(),
            source: nodes.length.toString(),
            target: (nodes.length + 3 - multiFlag).toString(),
            label: source[i].approve,
            style: {
              stroke: "brown",
              strokeWidth: 2,
            },
          });

          if (multiFlag === 2) {
            multiFlag = 0;
          }
        }
      }
      setFlowData({
        docid: docid,
        nodes: nodes,
        edges: edges,
      });
    }
  };

  const Oncancle = () => {
    setIsModalOpen(false);
  };

  const OncancleImg = () => {
    setIsModalOpenImg(false);
  };

  const OncanclePush = () =>{
    setIsModalOpenPush(false)
  }

  //強制執行流程操作之後渲染及提示--用戶不簽字時使用
  const OnSubmitPush = (docid:string) =>{
    const temp = dataSource
    temp.forEach(element => {
      if(element.docid === docid){
        element.next_push_flag = 'N'
      }
    });
    message.success('強制執行成功')
    setDataSource(temp)
    setIsModalOpenPush(false)
  }

  const nextPush = (docid:string)=>{
     setIsModalOpenPush(true)
     setCurDocid(docid)
  }

  const getQueryColumns: any = [
    {
      dataIndex: "docid",
      key: "docid",
      title: "單號",
      width: 140,
      render: (record: string) => {
        return (
          <span style={{ fontWeight: "600", color: "brown" }}>{record}</span>
        );
      },
    },
    {
      dataIndex: "badge",
      key: "badge",
      title: "工號",
      width: 60,
    },
    {
      dataIndex: "chinese_name",
      key: "chinese_name",
      title: "姓名",
      width: 100,
    },
    {
      dataIndex: "position",
      key: "position",
      title: "職位",
      width: 100,
    },
    {
      dataIndex: "status",
      key: "status",
      title: "狀態",
      width: 80,
    },
    {
      dataIndex: "assessment_result",
      key: "assessment_result",
      title: "面談結果",
      width: 100,
    },
    {
      dataIndex: "is_improve",
      key: "is_improve",
      title: "是否有改善計劃",
      width: 140,
    },
    {
      dataIndex: "docid",
      key: "check_info_2",
      title: "流程",
      width: 110,
      render: (docid: string) => {
        return (
          <>
            <Button
              type="primary"
              danger
              onClick={() => {
                CehckFlow(docid);
              }}
              icon={<TiFlowSwitch></TiFlowSwitch>}
            >
              查看流程
            </Button>
          </>
        );
      },
    },
    {
      dataIndex: "docid",
      key: "check_img",
      title: "查看簽名",
      width: 120,
      render: (docid: string) => {
        return (
          <Button
            type="primary"
            onClick={() => {
              setCurDocid(docid);
              setIsModalOpenImg(true);
            }}
            icon={<FaFileSignature></FaFileSignature>}
          >
            查看簽名
          </Button>
        );
      },
    },
    {
      dataIndex: "docid",
      key: "check_info",
      title: "詳情",
      width: 150,
      fixed: "right",
      render: (docid: string) => {
        const selOne = dataSource.filter((item) => item.docid === docid)[0];
        if (selOne.is_improve === "是" && selOne.next_push_flag === "Y") {
          return (
            <>
              <Tooltip title="點此查看績效面談表">
                <Button
                  type="primary"
                  onClick={() => {
                    CheckInfo(docid, "interview");
                  }}
                  icon={<PlusCircleFilled></PlusCircleFilled>}
                ></Button>
              </Tooltip>
              <Tooltip title="點此查看改善計劃表">
                <Button
                  style={{ marginLeft: "5px" }}
                  type="primary"
                  danger
                  onClick={() => {
                    CheckInfo(docid, "improve");
                  }}
                  icon={<PlusCircleFilled></PlusCircleFilled>}
                ></Button>
              </Tooltip>
              <Tooltip title="強制執行下一步流程">
                <Button
                  style={{ marginLeft: "5px" }}
                  type="primary"
                  danger
                  onClick={() => {
                    nextPush(docid)
                  }}
                  icon={<FaHandPointDown></FaHandPointDown>}
                ></Button>
              </Tooltip>
            </>
          );
        } else if (selOne.is_improve === "是" && selOne.next_push_flag === "N"
        ) {
          return (
            <>
              <Tooltip title="點此查看績效面談表">
                <Button
                  type="primary"
                  onClick={() => {
                    CheckInfo(docid, "interview");
                  }}
                  icon={<PlusCircleFilled></PlusCircleFilled>}
                ></Button>
              </Tooltip>
              <Tooltip title="點此查看改善計劃表">
                <Button
                  style={{ marginLeft: "5px" }}
                  type="primary"
                  danger
                  onClick={() => {
                    CheckInfo(docid, "improve");
                  }}
                  icon={<PlusCircleFilled></PlusCircleFilled>}
                ></Button>
              </Tooltip>
            </>
          );
        } else if (
          selOne.is_improve === "否" &&
          selOne.next_push_flag === "Y"
        ) {
          return (
            <>
              <Tooltip title="點此查看績效面談表">
                <Button
                  type="primary"
                  onClick={() => {
                    CheckInfo(docid, "interview");
                  }}
                  icon={<PlusCircleFilled></PlusCircleFilled>}
                ></Button>
              </Tooltip>
              <Tooltip title="強制執行下一步流程">
                <Button
                  style={{ marginLeft: "5px" }}
                  type="primary"
                  danger
                  onClick={() => {
                    nextPush(docid)
                  }}
                  icon={<FaHandPointDown></FaHandPointDown>}
                ></Button>
              </Tooltip>
            </>
          );
        } else {
          return (
            <>
              <Tooltip title="點此查看績效面談表">
                <Button
                  type="primary"
                  onClick={() => {
                    CheckInfo(docid, "interview");
                  }}
                  icon={<PlusCircleFilled></PlusCircleFilled>}
                ></Button>
              </Tooltip>
            </>
          );
        }
      },
    },
  ];

  const getTable = () => {
    if (dataSource.length > 0) {
      return (
        <Table
          dataSource={dataSource.map((item) => ({
            ...item,
            key: item.rowseq,
          }))}
          bordered={true}
          pagination={false}
          className="datasource-table"
          columns={getQueryColumns}
          style={{ marginTop: "5px" }}
          scroll={{ x: "max-content" }}
        ></Table>
      );
    }
  };

  const getPage = () => {
    if (pager.count > 0) {
      return (
        <Pagination
          current={pager.current}
          pageSize={pager.pagesize}
          style={{ marginTop: "20px" }}
          total={pager.count}
          onChange={(e) => {
            setPager({ ...pager, current: e });
            changeCurr(e);
          }}
        />
      );
    }
  };

  return (
    <>
      <div className="query-operator">
        <Form form={form}>
          <Form.Item
            name="docid"
            colon={false}
            className="query-input"
            label={<label className="form-label">單號:</label>}
          >
            <Input maxLength={14} className="query-input-item"></Input>
          </Form.Item>
          <Form.Item
            name="org_code"
            colon={false}
            className="query-input"
            label={<label className="form-label">廠區:</label>}
          >
            <Select
              options={orgList}
              onChange={(e) => {
                GetDeptFunc(e);
              }}
              className="query-input-item"
            ></Select>
          </Form.Item>
          <Form.Item
            name="dept"
            colon={false}
            className="query-input"
            label={<label className="form-label">部門:</label>}
          >
            <Select className="query-input-item" options={deptS}></Select>
          </Form.Item>
          <Form.Item
            name="decade"
            colon={false}
            className="query-input"
            label={<label className="form-label">期間:</label>}
          >
            <Input
              maxLength={6}
              placeholder="格式：YYYYMM"
              className="query-input-item"
            ></Input>
          </Form.Item>
          <Form.Item
            name="badge"
            colon={false}
            className="query-input"
            label={<label className="form-label">工號:</label>}
          >
            <Input maxLength={6} className="query-input-item"></Input>
          </Form.Item>
          <Form.Item
            name="submit"
            colon={false}
            className="query-input"
            style={{ width: "100px" }}
          >
            <Button
              type="primary"
              onClick={() => Submit()}
              icon={<MdManageSearch />}
            >
              查詢
            </Button>
          </Form.Item>
        </Form>
      </div>
      <Divider style={{ margin: "5px 0", background: "brown" }}></Divider>
      <div className="querymain-box">{getTable()}</div>
      <div>{getPage()}</div>
      <Modal
        closable={false}
        open={isModalOpen}
        width={700}
        style={{ top: "50px" }}
        wrapClassName="single-form"
        footer={[]}
      >
        <FLow data={flowData} onCancel={() => Oncancle()}></FLow>
      </Modal>
      <Modal
        closable={false}
        open={isModalOpenImg}
        width={700}
        style={{ top: "50px" }}
        wrapClassName="single-form"
        footer={[]}
      >
        <Download docid={curdocid} onCancle={() => OncancleImg()}></Download>
      </Modal>
      <Modal
        closable={false}
        open={isModalOpenPush}
        width={700}
        style={{ top: "50px" }}
        wrapClassName="single-form"
        footer={[]}
      >
        <PushFlow docid={curdocid} onCancel={() => OncanclePush()} onSubmit={OnSubmitPush}></PushFlow>
      </Modal>
    </>
  );
}
